#include <gst/interfaces/xoverlay.h>
#include <time.h>

#include "message_handler.h"
#include "http_client.h"
#include "xml_client.h"
#include "jpg_player.h"
#include "sys_log.h"
#include "url_config_win.h"
#include "printer_libgd.h"

volatile GList *http_status_list;
volatile int phpto_showing_flag = 0;
volatile gboolean wifi_flag = FALSE;
volatile int error_message_win_show_flag = 0;

static pthread_mutex_t glist_lock;

 typedef enum {
	message_cmd_print = 0,
	message_cmd_download,
	message_cmd_update_ad,
	message_cmd_update_version,
	message_cmd_change_qr,
	message_cmd_change_logo,
	message_cmd_change_bottom,
	message_cmd_echo
}http_message_handler_cmd_e;

typedef struct
{
	GtkWidget *window;

	time_t create_time;
	//cmd ID
	http_message_handler_cmd_e server_cmd;

	//file name
	char	file_name[1024];
	long	file_size;

	//pid code
	char	*pid;

	char 	*url;
	//ad
	char	*ad_id;

    //for print
    char   x[10];
    char   y[10];
    char   type[10];
    char*   text;

    //print control
    int printer_error;
    
}http_message_handler_s;


//http heart beat
#define POSTFIELDS "<?xml version=\"1.0\" ?><root>\
<FromUserName>%s</FromUserName>\
<ToUserName>%s</ToUserName>\
<MsgType></MsgType>\
<Event>printerstatus</Event>\
<EventKey>\
<content>%s</content>\
</EventKey>\
<Version>%s</Version>\
<CreateTime></CreateTime>\
<FuncFlag></FuncFlag>\
</root>"


static print_sys_config_s *handler_sys_config;


static char* get_version();
static http_message_handler_s* _glist_http_status_get(GList *glist,char* urlcontent);
static GList * _glist_http_status_add(GList *glist,http_message_handler_s* httpclient);
static GList * _glist_http_status_del(GList *glist,http_message_handler_s* httpclient);
static GList * _glist_http_status_clean_timeout(GList *glist);
static GList * _glist_http_status_clean_all(GList *glist);

/// there are two way to show photo, suggest use new win
/////show photo in video screen, video will pause
static gboolean show_photo_in_videoscreen_time_handler(GdkPixbuf *data)
{
	g_object_unref(data);
	player_continue();
	return FALSE;
}
static void show_photo_in_videoscreen(char* filename, GtkWidget* window)
{
	GdkPixbuf *src_pixbuf,*dst_pixbuf; 
	int w,h;

	gtk_widget_get_size_request(handler_sys_config->image_ad_main,&w,&h);

	player_pause();
	//gdk_window_clear(window->window);
	src_pixbuf = gdk_pixbuf_new_from_file(filename,NULL); 
	if (src_pixbuf ==NULL){   
		  SYS_LOG ("pixbuf create failed\n");
		  return;
	}
	dst_pixbuf=gdk_pixbuf_scale_simple(src_pixbuf,w,h,GDK_INTERP_BILINEAR);
	

	//gdk_pixbuf_render_to_drawable_alpha(dst_pixbuf, window->window, 0, 0,\
	//	0, 0, w, h,	GDK_PIXBUF_ALPHA_FULL, 0, GDK_RGB_DITHER_NONE, 0, 0);
	g_object_unref(src_pixbuf);
	g_timeout_add(5000,(GSourceFunc)show_photo_in_videoscreen_time_handler,dst_pixbuf);
}
//show photo end

#if 1
//show photo on new win
static gboolean show_photo_in_new_win_timeout(void *data)
{
//	g_print ("test_timeout in\n");
	update_image(handler_sys_config->image_photo,handler_sys_config->sys_config.image_photo_default);
	http_message_handler_s *http_message_handler = (http_message_handler_s *)data;

	remove(http_message_handler->file_name);
	gtk_widget_destroy(http_message_handler->window);
	http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
	phpto_showing_flag = 0;
	return FALSE;
}

static gboolean show_photo_in_new_win_loop(void *data)
{
	g_print ("show_photo_in_new_win_loop in\n");
	http_message_handler_s *http_message_handler = (http_message_handler_s *)data;
    show_photo_in_new_win(http_message_handler->file_name,http_message_handler);
   	g_print ("show_photo_in_new_win_loop out\n");
	return FALSE;
}


void show_photo_in_new_win(char* filename,http_message_handler_s * http_handler) 
{
   // GtkWidget *window;  
	GtkWidget *image;
	GdkPixbuf *src_pixbuf,*dst_pixbuf; 

    
    SYS_LOG("show_photo_in_new_win in");
    g_print("show_photo_in_new_win in\n"); 
	if(1 == phpto_showing_flag) {
        printf("sleep in\n");
        if(1 != http_handler->printer_error) {
            g_timeout_add(5000,(GSourceFunc)show_photo_in_new_win_loop,http_handler);
        }
        return;
	}
	phpto_showing_flag = 1;

    if (1 != http_handler->printer_error) {

        //photo operator
        printf("show_photo_in_new_win http_handler->type %s\n",http_handler->type);
        if(255 != atoi(http_handler->type)) {
            image_generateImg(http_handler->file_name,http_handler->text,handler_sys_config->sys_config.image_bottom,atoi(http_handler->x),atoi(http_handler->y),0,0,atoi(http_handler->type),handler_sys_config->sys_config.text_font_path);
        } else {
            image_generateImg_with_userinfo(http_handler->file_name,http_handler->text,handler_sys_config->sys_config.image_bottom,atoi(http_handler->type),handler_sys_config->sys_config.text_font_path);
        }
        //print file
            printf("show_photo_in_new_win in print\n");
        if(0 == access(http_handler->file_name,F_OK)) {
            printing_file(http_handler->file_name);
        }
            printf("show_photo_in_new_win in print end\n");
    }

	src_pixbuf = gdk_pixbuf_new_from_file(filename,NULL); 
    g_print("show_photo_in_new_win in 002\n");
	if (src_pixbuf == NULL){   
		  g_print ("show_photo_in_new_win pixbuf create failed\n");
          http_status_list = _glist_http_status_del((GList*)http_status_list,http_handler);   
          phpto_showing_flag = 0;
		  return;
	}

    http_handler->window=gtk_window_new(GTK_WINDOW_POPUP);
    gtk_window_fullscreen(GTK_WINDOW(http_handler->window));
	
	gint w =  gdk_pixbuf_get_width(src_pixbuf);
 	gint h =  gdk_pixbuf_get_height(src_pixbuf);
    gint dst_w = w*0.5;
    gint dst_h = h*0.5*0.9;
    g_print("show_photo_in_new_win in 003\n");
    if(1 == http_handler->printer_error) {
        dst_w = 750*0.5;
        dst_h = 1050*0.5*0.9;
    }

    //choose screen position

	if(NULL == g_strrstr(handler_sys_config->sys_config.screen_module,"big_screen")) {
        g_print ("show_photo_in_new_win four screen\n");
        gtk_window_move(GTK_WIDGET(http_handler->window),handler_sys_config->screen_w*0.1*0.5+handler_sys_config->fs_left_fix_w-5*handler_sys_config->fs_pad,handler_sys_config->screen_h*0.1*0.5+handler_sys_config->fs_usr_text_h+2*handler_sys_config->fs_pad);
	} else {
	    printf("show big pic\n");
        dst_w = w*0.5*0.9;
        dst_h = h*0.5*0.9;
        gtk_window_move(GTK_WIDGET(http_handler->window),handler_sys_config->screen_w*0.1*0.5+2*handler_sys_config->bs_pad,handler_sys_config->screen_h*0.2*0.5+handler_sys_config->bs_qr_img_h+handler_sys_config->bs_pad);
	}
    g_print("show_photo_in_new_win in 004\n");
    gtk_widget_set_size_request(GTK_WIDGET(http_handler->window),dst_w,dst_h);
    //  gtk_window_set_position( GTK_WINDOW(http_handler->window), GTK_WIN_POS_CENTER_ALWAYS);

	dst_pixbuf=gdk_pixbuf_scale_simple(src_pixbuf,dst_w,dst_h,GDK_INTERP_BILINEAR);	
	image=gtk_image_new();   
	gtk_image_set_from_pixbuf((GtkImage *)image,dst_pixbuf);	   
	g_object_unref(src_pixbuf); 
	g_object_unref(dst_pixbuf); 
	gtk_container_add(GTK_CONTAINER(http_handler->window),image);  
	gtk_widget_show(image);    
	gtk_widget_show_all(http_handler->window);
	g_timeout_add(20000,(GSourceFunc)show_photo_in_new_win_timeout,http_handler);

    g_print("show_photo_in_new_win out\n"); 
}
//show photo on new win end




#else
//show photo on new win
static gboolean show_photo_in_new_win_timeout(GtkWidget *data)
{
	update_image(handler_sys_config->image_photo,handler_sys_config->sys_config.image_photo_default);
	http_message_handler_s *http_message_handler = (http_message_handler_s *)data;

	//remove(http_message_handler->file_name);
	http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
	phpto_showing_flag = 0;
	return FALSE;
}

void show_photo_in_new_win(char* filename, http_message_handler_s * http_handler) 
{
    GtkWidget *window;  
	GtkWidget *image;
	GdkPixbuf *src_pixbuf,*dst_pixbuf; 

	while(1 == phpto_showing_flag) {
		SYS_LOG("show_photo_in_new_win sleep [%s]",filename);
		sleep(3);
	}
	phpto_showing_flag = 1;

	update_image_with_default(handler_sys_config->image_photo,filename);
	
	g_timeout_add(10000,(GSourceFunc)show_photo_in_new_win_timeout,http_handler);
}
//show photo on new win end
#endif

//wifi on or off control
static void check_update_wifi_img(gboolean netstat)
{

	if(FALSE == netstat && TRUE == wifi_flag) {
		SYS_LOG("------------wifi off------------");
		update_image(handler_sys_config->image_wifi,handler_sys_config->sys_config.image_wifi_off);
		wifi_flag = FALSE;
	} else if(TRUE == netstat && FALSE == wifi_flag) {
		SYS_LOG("------------wifi on------------");
		update_image(handler_sys_config->image_wifi,handler_sys_config->sys_config.image_wifi_on);
		wifi_flag = TRUE;
	}
	return;
}

static void* destory_http_message_handler_s(http_message_handler_s *message_handler)
{
	if (NULL == message_handler) return;

	if (NULL != message_handler->url) free( message_handler->url);
	if (NULL != message_handler->pid) free( message_handler->pid);
	if (NULL != message_handler->ad_id) free( message_handler->ad_id);
   	if (NULL != message_handler->text) free( message_handler->text);
	//remove(message_handler->file_name);
	free(message_handler);
	return;
}

static void http_recv_cb(char* buf, long buf_len, char* content_type, void* usr_data)
{
	http_message_handler_s *http_message_handler = (http_message_handler_s *)usr_data;

	switch(http_message_handler->server_cmd) {
		case message_cmd_download:
			{
				if(get_file_size(buf) < 1024){
					SYS_LOG("message_cmd_download error: too small");
					remove(buf);
					http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
					break;
				}
				if(g_strrstr(buf,".mp4")) {
					player_read_filelist();
				}	
				http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);
			}
			break;
		case message_cmd_print:
			{
				if(get_file_size(http_message_handler->file_name) < 1024){
					SYS_LOG("message_cmd_print error: too small");
					remove(http_message_handler->file_name);
					http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
					break;
				}
				show_photo_in_new_win(buf,http_message_handler);
			}
			break;
		case message_cmd_update_ad:
			{
				if(get_file_size(buf) < 1024){
					
					SYS_LOG("message_cmd_update_ad error: too small");
					remove(buf);
					http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
					break;
				}

				jpg_player_update_jpg(http_message_handler->file_name,http_message_handler->ad_id);
				http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
			}
			break;

		case message_cmd_update_version://tar and reboot
			{
				char path[200] = {0};
				FILE *fp;

				SYS_LOG("!!message_cmd_update_version begin!!");

				if(0 != access(http_message_handler->file_name,F_OK)) { 
					SYS_LOG("message_cmd_update_version error: no file");
					break;
				}
				if(get_file_size(http_message_handler->file_name) < 20*1024) { 
					SYS_LOG("message_cmd_update_version error: too small");
					remove(http_message_handler->file_name);
					break;
				}
				if(0 != access("update.tar.gz",F_OK)) { 
					remove("update.tar.gz");
				}
				rename(buf,"update.tar.gz");
				//sprintf(path,"tar -zxvf %s -C ../",buf);
				//SYS_LOG("set path[%s]\n",path);
//				fp = popen("sudo tar -zxvf update.tar.gz -C ../", "r");
				fp = popen("gnome-terminal -x tar -zxvf update.tar.gz -C ../", "r");
				pclose(fp);
				fp = popen("gnome-terminal -x sudo chmod -R 777 ../bin", "r");
				pclose(fp);
				//remove(buf);
				http_status_list = _glist_http_status_clean_all((GList*)http_status_list);
                //save config
                strcpy(handler_sys_config->sys_config.updated_flag,"yes");
                save_text_config_file(CLIENT_SYS_CONFIG_FILE,&(handler_sys_config->sys_config));
                
			    pthread_mutex_destroy(&glist_lock);
				free(handler_sys_config);
				sys_log_close();
				gtk_main_quit();
			}
			break;
		case message_cmd_change_qr://change qr pic
			{
				if(get_file_size(buf) < 1024){
					SYS_LOG("message_cmd_change_qr error: too small");
					remove(buf);
					http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
					break;
				}
				if(0 == access(handler_sys_config->sys_config.image_qr,F_OK)) {
					remove(handler_sys_config->sys_config.image_qr);
					rename(buf,handler_sys_config->sys_config.image_qr);
				}
				http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);
				update_image(handler_sys_config->image_qr_code,handler_sys_config->sys_config.image_qr);
			}

			break;
		case message_cmd_change_logo://change logo
			{
				if(get_file_size(buf) < 1024){
					SYS_LOG("message_cmd_change_logo error: too small");
					remove(buf);
					http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);	
					break;
				}

				if(0 == access(handler_sys_config->sys_config.image_logo,F_OK)) {
					remove(handler_sys_config->sys_config.image_logo);
					rename(buf,handler_sys_config->sys_config.image_logo);
				}
				http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);
				update_image(handler_sys_config->image_logo,handler_sys_config->sys_config.image_logo);
			}
			break;

            case message_cmd_change_bottom://change bottom
            {
                if(get_file_size(buf) < 1024){
                    SYS_LOG("message_cmd_change_logo error: too small");
                    remove(buf);
                    http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);   
                    break;
                }
                if(0 == access(handler_sys_config->sys_config.image_bottom,F_OK)) {
                    remove(handler_sys_config->sys_config.image_bottom);
                    rename(buf,handler_sys_config->sys_config.image_bottom);
                }
                http_status_list = _glist_http_status_del((GList*)http_status_list,http_message_handler);
            }
            break;

		case message_cmd_echo://donothing
			break;
		default:
			break;
	}

	//destory_http_message_handler_s(http_message_handler);
}

static void* _create_httpclient_session(void *data)
{

	http_message_handler_s *http_message_handler = (http_message_handler_s *)data;
	http_status_list = _glist_http_status_add((GList*)http_status_list,http_message_handler);

	switch(http_message_handler->server_cmd) {

		case message_cmd_print:
			sprintf(http_message_handler->file_name,"%s%s%s",BASE_PATH,PIC_PATH,g_strrstr(http_message_handler->url,"/")); //photos
			break;
		case message_cmd_update_version://tar and reboot
			sprintf(http_message_handler->file_name,"%s%s",BASE_PATH,g_strrstr(http_message_handler->url,"/")); // update package
			break;
		case message_cmd_download:
			sprintf(http_message_handler->file_name,"%s%s%s",BASE_PATH,MP4_PATH,g_strrstr(http_message_handler->url,"/")); //ad mp4
			break;
		case message_cmd_update_ad:
		case message_cmd_change_qr://change qr pic
		case message_cmd_change_logo://change logo
			sprintf(http_message_handler->file_name,"%s%s%s",BASE_PATH,AD_PATH,g_strrstr(http_message_handler->url,"/")); //photos
			break;
        case message_cmd_change_bottom:
			sprintf(http_message_handler->file_name,"%s%s%s",BASE_PATH,AD_PATH,g_strrstr(http_message_handler->url,"/")); //photos
            break;
		case message_cmd_echo://donothing
			break;
		default:
			break;
	}
//	SYS_LOG("http_message_handler->file_name is [%s]\n",http_message_handler->file_name);
	get_data_by_url(http_message_handler->url,http_message_handler->file_name,http_recv_cb,http_message_handler);
}


	
/*
	char *testurl1 = g_strdup("http://d.hiphotos.baidu.com/image/w%3D2048/sign=73bfd8fe9d3df8dca63d8891f929738b/9f510fb30f2442a7da432bacd343ad4bd113026d.jpg");
	char *testurl2 = g_strdup("http://a.hiphotos.baidu.com/image/w%3D2048/sign=910aed6f544e9258a63481eea8bad058/4610b912c8fcc3ce5bd4cc389045d688d43f20a0.jpg");
	char *testurl3 = g_strdup("http://d.hiphotos.baidu.com/image/w%3D2048/sign=dfb6f480c9ef76093c0b9e9f1ae5a2cc/2cf5e0fe9925bc318f22f1855cdf8db1cb1370b4.jpg");
*/

//#define TEST_XML_DATA "<?xml version=\"1.0\" ?><root><FromUserName></FromUserName><ToUserName></ToUserName><MsgType></MsgType><Event>download</Event><EventKey><content>http://d.hiphotos.baidu.com/image/w%3D2048/sign=73bfd8fe9d3df8dca63d8891f929738b/9f510fb30f2442a7da432bacd343ad4bd113026d.jpg</content><content>http://a.hiphotos.baidu.com/image/w%3D2048/sign=910aed6f544e9258a63481eea8bad058/4610b912c8fcc3ce5bd4cc389045d688d43f20a0.jpg</content><content>http://d.hiphotos.baidu.com/image/w%3D2048/sign=dfb6f480c9ef76093c0b9e9f1ae5a2cc/2cf5e0fe9925bc318f22f1855cdf8db1cb1370b4.jpg</content></EventKey><Version>%s</Version><CreateTime></CreateTime><FuncFlag></FuncFlag></root>"
//#define TEST_XML_DATA "<?xml version=\"1.0\" ?><root><FromUserName><![CDATA[print_server]]></FromUserName><ToUserName><![CDATA[ac-72-89-57-06-0c]]></ToUserName><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[change_usr_text]]></Event><EventKey><content><![CDATA[step1: send a picture to me]]></content><content><![CDATA[step2: edit the picture]]></content><content><![CDATA[step3: send text to me ]]></content><content><![CDATA[setp4: send verify code to me]]></content></EventKey><Version>1.0</Version><CreateTime>1396361412</CreateTime><FuncFlag>0</FuncFlag></root>"
//#define TEST_XML_DATA "<?xml version=\"1.0\" ?><root><FromUserName><![CDATA[print_server]]></FromUserName><ToUserName><![CDATA[ac-72-89-57-06-0c]]></ToUserName><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[change_qr]]></Event><EventKey><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&type=qr&picname=9.jpg]]></EventKey><Version>1.0</Version><CreateTime>1396362805</CreateTime><FuncFlag>0</FuncFlag></root>"

#define TEST_XML_DATA "<?xml version=\"1.0\" ?><root><FromUserName><![CDATA[print_server]]></FromUserName><ToUserName><![CDATA[ac-72-89-57-06-0c]]></ToUserName><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[print]]></Event><EventKey><content><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&picname=lomo139636734818.jpg]]></content></EventKey><Version>1.0</Version><CreateTime>1396367361</CreateTime><FuncFlag>0</FuncFlag></root>"
//#define TEST_XML_DATA "<?xml version=\"1.0\" ?><root><FromUserName><![CDATA[gh_a53ada087c0d]]></FromUserName><ToUserName><![CDATA[print_user1]]></ToUserName><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[update_ad]]></Event><EventKey><content><![CDATA[main2]]></content><content><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&type=ad&picname=mid_19.jpg]]></content><content><![CDATA[main3]]></content><content><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&type=ad&picname=mid_19.jpg]]></content><content><![CDATA[left]]></content><content><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&type=ad&picname=mid_19.jpg]]></content><content><![CDATA[middle]]></content><content><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&type=ad&picname=mid_19.jpg]]></content><content><![CDATA[right]]></content><content><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&type=ad&picname=mid_19.jpg]]></content><content><![CDATA[main1]]></content><content><![CDATA[http://112.124.103.153/webprint/image.php?act=printimage&type=ad&picname=mid_19.jpg]]></content></EventKey><Version>1.0</Version><CreateTime>1396368366</CreateTime><FuncFlag>0</FuncFlag></root>"


static int test_test = 0;

static gboolean server_print_timeout(void *data)
{
	char* file_path = (char*)data;
	if(0 == access(file_path,F_OK)) {
		printing_file(file_path);
	}
}
static gboolean _screen_mode_change_timeout(void *data)
{
    http_status_list = _glist_http_status_clean_all((GList*)http_status_list);
    pthread_mutex_destroy(&glist_lock);
    free(handler_sys_config);
    handler_sys_config = NULL;
    sys_log_close();
    gtk_main_quit();

}

static void handler_net_error(char* buf, long buf_len)
{
    SYS_LOG("handler_net_error in\n");
    error_message_win_show_flag = 1;
    if (NULL != g_strrstr(buf,"error hash")) {
        show_message_win(handler_sys_config,"设备编号错误：请检查服务器地址和设备编号配置");
    } else if (NULL != g_strrstr(buf,"mac error")) {
        show_message_win(handler_sys_config,"设备mac错误：请检查服务器地址和设备mac地址配置");
    } else if (NULL != g_strrstr(buf,"updated")) {
        show_message_win(handler_sys_config,"设备版本已更新成功！");
    }else{
        show_message_win(handler_sys_config,"未知错误");
    } 
}


static void http_heartbeat_recv_cb(char* buf, long buf_len, char* content_type, void* usr_data)
{
	int pthreadStatus = 0;
	pthread_t pthreadId = 0;
	char* buf_ptr = NULL;
	char* node_value = NULL;

	if(NULL == buf || NULL == content_type) {
		SYS_LOG("http_heartbeat_recv_cb buf null\n");
		return;
	}

	if (0 == buf_len) {
		SYS_LOG("http_heartbeat_recv_cb receive error\n");
		return;
	}

	buf_ptr = buf;


#if 0 //test
//	buf_ptr = strstr(buf,"\r\n\r\n") + 4;
//	buf_len = strlen(buf_ptr);
	if(test_test==1) return;
	buf_ptr = TEST_XML_DATA;
	buf_len = strlen(buf_ptr);
	test_test = 1;
#endif
	char log[200] = {0};
	sprintf(log,"*********http_recv_cb data[%%ld]******\n %%.%lds \n",buf_len);


    if(0 == strcmp(handler_sys_config->sys_config.updated_flag,"yes")){
        strcpy(handler_sys_config->sys_config.updated_flag,"no");
   		save_text_config_file(CLIENT_SYS_CONFIG_FILE,&(handler_sys_config->sys_config));
        handler_net_error("updated version",20);
        return;
    }

    if(buf_len<100) { //error
        printf("handler_net_error in\n");
        handler_net_error(buf_ptr,buf_len);
        return;
    }


	void* xml_handler =  parse_xml_buf(buf_ptr,buf_len);
	void* event_node = parse_get_xml_node_value_from_handler(xml_handler,"Event",&node_value);

	//handler event
	char* url_content = NULL;
	void* Eventkey_node = parse_get_xml_node_value_from_handler(xml_handler,"EventKey",NULL);
	void* url_node = parse_get_xml_node_value_from_node(Eventkey_node,"content",&url_content);

    if(error_message_win_show_flag == 1) {
        printf("hide_message_win in\n");
        error_message_win_show_flag = 0;
        hide_message_win(handler_sys_config);
    }

	if (url_node == NULL || url_content == NULL) {
//		SYS_LOG("------ parse error, node_value[%s]-----",node_value);
		xmlFree(node_value);
		parse_xml_buf_finish(xml_handler);
		return;
	}
	SYS_LOG("------node_value[%s]-----",node_value);
//	SYS_LOG(log, buf_len,buf_ptr);

	if (0 == strcmp(node_value,"print")) {
		SYS_LOG("**********######PRINT######************");

		while(NULL != url_node) {// content1:url  | content2:x  | content3:y | content4:text | content5:type
			SYS_LOG("PRINT LOOP !!!!!!!!\n");
   			printf("PRINT LOOP !!!!!!!!\n");
			http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
			memset(http_message_handler,0,sizeof(http_message_handler_s));
			http_message_handler->server_cmd = message_cmd_print;
			http_message_handler->url = g_strdup(url_content);
			time(&http_message_handler->create_time);
			xmlFree(url_content);

            // x
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
            g_stpcpy(http_message_handler->x,url_content);
			xmlFree(url_content);
            // y
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
            g_stpcpy(http_message_handler->y,url_content);
			xmlFree(url_content);
            // text
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
            http_message_handler->text= g_strdup(url_content);
			xmlFree(url_content);
            // type
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
            g_stpcpy(http_message_handler->type,url_content);
			xmlFree(url_content);


            //          pthreadStatus = pthread_create(&pthreadId, NULL, _create_httpclient_session, http_message_handler);
			_create_httpclient_session(http_message_handler);

			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
            SYS_LOG("PRINT LOOP\n");
            printf("PRINT LOOP ---------\n");
			//sleep(3);
		}

	}else if (0 == strcmp(node_value,"update_version")) {//todo
	
		SYS_LOG("**********######update_version in######************");

		http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
		memset(http_message_handler,0,sizeof(http_message_handler_s));
		http_message_handler->server_cmd = message_cmd_update_version;
		http_message_handler->url = g_strdup(url_content);
		time(&http_message_handler->create_time);
		xmlFree(url_content);

		if(NULL != url_content) {
			pthreadStatus = pthread_create(&pthreadId, NULL, _create_httpclient_session, http_message_handler);
		}
		
	}else if (0 == strcmp(node_value,"download")) {
		SYS_LOG("------download----- in");

		while(NULL != url_node) {
			
			http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
			memset(http_message_handler,0,sizeof(http_message_handler_s));
			http_message_handler->server_cmd = message_cmd_download;
			http_message_handler->url = g_strdup(url_content);
			time(&http_message_handler->create_time);
			xmlFree(url_content);
			pthreadStatus = pthread_create(&pthreadId, NULL, _create_httpclient_session, http_message_handler);
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
		}
		
	}else if (0 == strcmp(node_value,"update_ad")) {
		SYS_LOG("------update_ad----- in");

		while(NULL != url_node) {
			char* ad_url = NULL;
			
			url_node = parse_get_xml_node_value_next(url_node,"content",&ad_url);
			http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
			memset(http_message_handler,0,sizeof(http_message_handler_s));
			http_message_handler->server_cmd = message_cmd_update_ad;
			http_message_handler->url = g_strdup(ad_url);
			http_message_handler->ad_id = g_strdup(url_content);
			time(&http_message_handler->create_time);
			xmlFree(url_content);
			xmlFree(ad_url);
            //          pthreadStatus = pthread_create(&pthreadId, NULL, _create_httpclient_session, http_message_handler);
            _create_httpclient_session(http_message_handler);

			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
			
		}
	}else if (0 == strcmp(node_value,"change_qr")) {

		//response do nothing
		SYS_LOG("------change_qr----- in");
		http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
		memset(http_message_handler,0,sizeof(http_message_handler_s));
		http_message_handler->server_cmd = message_cmd_change_qr;
		http_message_handler->url = g_strdup(url_content);
		time(&http_message_handler->create_time);
		xmlFree(url_content);
		pthreadStatus = pthread_create(&pthreadId, NULL, _create_httpclient_session, http_message_handler);
	}else if (0 == strcmp(node_value,"change_bottom_pic")) {

		//response do nothing
		SYS_LOG("------change_bottom_pic----- in");
		http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
		memset(http_message_handler,0,sizeof(http_message_handler_s));
		http_message_handler->server_cmd = message_cmd_change_bottom;
		http_message_handler->url = g_strdup(url_content);
		time(&http_message_handler->create_time);
		xmlFree(url_content);
		pthreadStatus = pthread_create(&pthreadId, NULL, _create_httpclient_session, http_message_handler);
	}else if (0 == strcmp(node_value,"change_logo")) {
		SYS_LOG("------change_logo----- in");

		//response do nothing
		http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
		memset(http_message_handler,0,sizeof(http_message_handler_s));
		http_message_handler->server_cmd = message_cmd_change_logo;
		http_message_handler->url = g_strdup(url_content);
		time(&http_message_handler->create_time);
		xmlFree(url_content);
		pthreadStatus = pthread_create(&pthreadId, NULL, _create_httpclient_session, http_message_handler);
	}else if (0 == strcmp(node_value,"change_code")) { // show spend code
	    if (0 == strcmp(handler_sys_config->sys_config.printer_mode,"free")) {
    		sprintf(handler_sys_config->sys_config.code,"%s",url_content);
    		update_text(handler_sys_config->label_code,url_content,20000);
    		save_text_config_file(CLIENT_SYS_CONFIG_FILE,&(handler_sys_config->sys_config));
        }
	}else if (0 == strcmp(node_value,"change_printer_mode")) { // printer mode for show or not show spend code on screen

		SYS_LOG("------change_printer_mode----- ");
		sprintf(handler_sys_config->sys_config.printer_mode,"%s",url_content);
		save_text_config_file(CLIENT_SYS_CONFIG_FILE,&(handler_sys_config->sys_config));
        if(0 == strcmp(url_content,"nofree")) {
            SYS_LOG("------change_printer_mode--hide--- ");
         	gtk_widget_hide(handler_sys_config->label_code);
        } else {
            SYS_LOG("------change_printer_mode- show---- ");
           	update_text(handler_sys_config->label_code,handler_sys_config->sys_config.code,20000);
        }
	}else if (0 == strcmp(node_value,"change_usr_text")) { // show spend code
		if(NULL != url_node) {
			sprintf(handler_sys_config->sys_config.right_label_1,"%s",url_content);
			SYS_LOG("usr_text_01: %s",url_content);
			update_text(handler_sys_config->label_text_1,url_content,20000);
			xmlFree(url_content);
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
		}
		if(NULL != url_node) {
			sprintf(handler_sys_config->sys_config.right_label_2,"%s",url_content);
			SYS_LOG("usr_text_02: %s",url_content);
			update_text(handler_sys_config->label_text_2,url_content,20000);
			xmlFree(url_content);
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
		}
		if(NULL != url_node) {
			sprintf(handler_sys_config->sys_config.right_label_3,"%s",url_content);
			SYS_LOG("usr_text_03: %s",url_content);
			update_text(handler_sys_config->label_text_3,url_content,20000);
			xmlFree(url_content);
			url_node = parse_get_xml_node_value_next(url_node,"content",&url_content);
		}
		if(NULL != url_node) {
			SYS_LOG("usr_text_04: %s",url_content);
			sprintf(handler_sys_config->sys_config.right_label_4,"%s",url_content);
			update_text(handler_sys_config->label_text_4,url_content,20000);
			xmlFree(url_content);
		}
		save_text_config_file(CLIENT_SYS_CONFIG_FILE,&(handler_sys_config->sys_config));
		
	}else if (0 == strcmp(node_value,"change_machine_id")) { // show spend code
		sprintf(handler_sys_config->sys_config.device_id,"%s",url_content);
		update_text(handler_sys_config->device_id_text,url_content,15000);
		save_text_config_file(CLIENT_SYS_CONFIG_FILE,&(handler_sys_config->sys_config));
	}else if (0 == strcmp(node_value,"change_ui_mode")) { // show spend code
		SYS_LOG("------change_ui_mode----- ");
        if(0 != strcmp(handler_sys_config->sys_config.screen_module,url_content)) {
            SYS_LOG("------change_ui_mode-----on ");
    		sprintf(handler_sys_config->sys_config.screen_module,"%s",url_content);
    		save_text_config_file(CLIENT_SYS_CONFIG_FILE,&(handler_sys_config->sys_config));
           	g_timeout_add(25000,(GSourceFunc)_screen_mode_change_timeout,handler_sys_config);
        }
	}else{// not know type , donothing
	
	}
	xmlFree(node_value);
	parse_xml_buf_finish(xml_handler);
}


static gboolean server_heartbeat_message_timeout(void *data)
{
	char*	tmp_buf = get_version();
	char 	xml_buf[1024] = {0};
	char	url[256] = {0};
	gboolean net_status;
	//create xml buf

	char* print_status = NULL;
	
	if (1 == printing_get_status()) {
		print_status = g_strdup("ok");
	} else {
		print_status = g_strdup("error");
        printf(" \n\n ***server_heartbeat_message_timeout  printer error***\n");
/*
        http_message_handler_s *http_message_handler = (http_message_handler_s *)malloc(sizeof(http_message_handler_s));
        memset(http_message_handler,0,sizeof(http_message_handler_s));
        http_message_handler->server_cmd = message_cmd_update_ad;
        http_message_handler->printer_error = 1;
        time(&http_message_handler->create_time);
        http_status_list = _glist_http_status_add((GList*)http_status_list,http_message_handler);
        show_photo_in_new_win(handler_sys_config->sys_config.printer_error_pic,http_message_handler);
*/
	}
	
	sprintf(xml_buf,POSTFIELDS,handler_sys_config->sys_config.eth0_mac_addr,"print_server",print_status,tmp_buf);//add version
	sprintf(url,"%s",handler_sys_config->sys_config.heart_beat_url);//add version

	if(NULL != print_status) free(print_status);
	if(NULL != tmp_buf) free(tmp_buf);

	//SYS_LOG ("server_heartbeat_message_timeout in**************\n %s \n",xml_buf);
	
	if (HEART_BEAT_PROTOCAL == 1) {
		net_status = http_heart_beat_post(url,xml_buf,http_heartbeat_recv_cb,data);
		check_update_wifi_img(net_status);
	} else {
		tcp_heart_beat_post(POSTFIELDS);
	}
	
	//check list
	
	return TRUE;
}


static gboolean server_clear_http_status_timeout(void *data)
{
	
	//create xml buf
	http_status_list=_glist_http_status_clean_timeout((GList*)http_status_list);
	//check list
	return TRUE;
}


void server_heartbeat_message(print_sys_config_s *sys_config) // 0: tcp, 1:http
{
	// 5s
	pthread_mutex_init(&glist_lock,NULL);
	handler_sys_config = sys_config;

	g_timeout_add(5000,(GSourceFunc)server_heartbeat_message_timeout,sys_config);
	g_timeout_add(1000*60*60*3,(GSourceFunc)server_clear_http_status_timeout,sys_config);
}

static char* get_version()
{
	return g_strdup("0.0.1");
}

static http_message_handler_s* _glist_http_status_get(GList *glist,char* urlcontent)
{

	GList *first;
	if (glist == NULL || urlcontent == NULL) {
		return NULL;
	}

	first = g_list_first(glist);
	http_message_handler_s *client = NULL;
	for (; first; first = g_list_next(first)) {
		client = (http_message_handler_s *)first->data;
		if(0 == strcmp(urlcontent,client->url)) {
			return client;
		}
	}
	return NULL;
}

static GList * _glist_http_status_add(GList *glist,http_message_handler_s* httpclient)
{
	if (glist == NULL || httpclient == NULL) {
		return glist;
	}
	pthread_mutex_lock(&glist_lock);
	glist = g_list_append(glist,httpclient);
	pthread_mutex_unlock(&glist_lock);
	return glist;
}


static GList * _glist_http_status_del(GList *glist,http_message_handler_s* httpclient)
{

	GList *first;
	GList *tmp = NULL;
	http_message_handler_s* client=NULL;
	if (glist == NULL || httpclient == NULL) {
		return glist;
	}
	pthread_mutex_lock(&glist_lock);
	for (; first; first = g_list_next(first)) {
		client = (http_message_handler_s *)first->data;

		if(httpclient == client) {
			destory_http_message_handler_s(client);
			glist = g_list_remove(glist,client);
			break;
		}
	}
	pthread_mutex_unlock(&glist_lock);
	return glist;
}

static GList * _glist_http_status_clean_timeout(GList *glist)
{

	GList *first;
	time_t curTime;
	http_message_handler_s* client=NULL;
	int time_out = 60*60*24; // 1 day
		
	time(&curTime);

	if (glist == NULL) {
		return glist;
	}
	pthread_mutex_lock(&glist_lock);

	for (; first; first = g_list_next(first)) {
		client = (http_message_handler_s *)first->data;

		if(client->create_time+time_out > curTime) {
			destory_http_message_handler_s(client);
			glist = g_list_remove(glist,client);
		}
	}
	pthread_mutex_unlock(&glist_lock);
	return glist;
}

static GList * _glist_http_status_clean_all(GList *glist)
{

	GList *first;
	time_t curTime;
	http_message_handler_s* client=NULL;
	int time_out = 60*60*24; // 1 day
		
	time(&curTime);

	if (glist == NULL) {
		return glist;
	}
	pthread_mutex_lock(&glist_lock);

	for (; first; first = g_list_next(first)) {
		client = (http_message_handler_s *)first->data;
		destory_http_message_handler_s(client);
	}
	g_list_free(glist);
	pthread_mutex_unlock(&glist_lock);
	return NULL;
}


